/*********************************************************************************
 *      Copyright:  (C) 2018 www.kansnow.com
 *                  All rights reserved.
 *
 *       Filename:  tttttttttt.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(06/06/2018)
 *         Author:  zhoupiaolong <zhoupiaolong@gmail.com>
 *      ChangeLog:  1, Release initial version on "06/06/2018 11:04:25 PM"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>

#define BUF_SIZE 1024

void getPidByName(pid_t *pid, char *task_name);

int main()
{
    pid_t pid = 0;
    char task_name[] = "test";

    getPidByName(&pid, task_name);

    return 0;
}

//通过进程名获取pid号
void getPidByName(pid_t *pid, char *task_name)
 {
     DIR *dir;
     struct dirent *ptr;
     FILE *fp;
     char filepath[50];
     char cur_task_name[50];
     char buf[BUF_SIZE];
 
     dir = opendir("/proc"); 
     if (NULL != dir)
     {
         while ((ptr = readdir(dir)) != NULL)  //循环读取/proc下的每一个文件/文件夹
         {
             //如果读取到的是"."或者".."则跳过，读取到的不是文件夹名字也跳过
             if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
                 continue;
             if (DT_DIR != ptr->d_type)
                 continue;
            
             sprintf(filepath, "/proc/%s/status", ptr->d_name); //生成要读取的文件的路径
             fp = fopen(filepath, "r");
             if (NULL != fp)
             {
                 if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
                     fclose(fp);
                     continue;
                 }
                 sscanf(buf, "%*s %s", cur_task_name);
                //如果文件内容满足要求则打印路径的名字（即进程的PID）   
                 if (!strcmp(task_name, cur_task_name)){
                     printf("filepath = %s\n", filepath);
                     printf("buf = %s\n", buf);
                     printf("before pid = %s\n", ptr->d_name);
                     sscanf(ptr->d_name, "%d", pid);
                 }
                 fclose(fp);
             }
         }
         closedir(dir);
     }
 } 
